package com.zam.utils;

import com.github.hui.quick.plugin.qrcode.helper.QrCodeGenerateHelper;
import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenWrapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author talent_dog
 * @Date 2024/3/22 21:36
 * @Version 1.0
 */
public class QRCode {

    //使用开源项目qrcode生成普通黑白二维码
    public static void BWQRCode(String str, HttpServletResponse response) throws Exception {
        BufferedImage bufferedImage = QrCodeGenWrapper.of(str)
                .asBufferedImage();
        ImageIO.write(bufferedImage, "png", response.getOutputStream());
    }
    //使用开源项目qrcode生成带logo二维码
//    public static void BWQRCode(String str, HttpServletResponse response) throws Exception {
//        BufferedImage bufferedImage = QrCodeGenWrapper.of(str)
//                .setLogo()
//                .asBufferedImage();
//        ImageIO.write(bufferedImage, "png", response.getOutputStream());
//    }

    //使用zxing生成黑白二维码
    public static void createQRCode(String str, HttpServletResponse response) throws Exception {

        //设置二维码参数
        Map map = new HashMap();
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        map.put(EncodeHintType.MARGIN, 1);

        //生成二维码
        MultiFormatWriter mfw = new MultiFormatWriter();
        BitMatrix encode = mfw.encode(str, BarcodeFormat.QR_CODE, 300, 300, map);
        int height = encode.getHeight();
        int width = encode.getWidth();

        //获取图片流
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, encode.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        //输出图片流
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "png", out);
        out.flush();
        out.close();

    }
}
